﻿#include "udpclient.h"
#include <QByteArray>
#include <QDebug>

UdpClient::UdpClient(const QHostAddress &serverAddress, quint16 serverPort, QObject *parent)
    : QObject(parent), m_serverAddress(serverAddress), m_serverPort(serverPort), udpSocket(new QUdpSocket(this))
{
    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpClient::readPendingDatagrams);
}

UdpClient::~UdpClient() {
    udpSocket->abort();
    udpSocket->deleteLater();
}

bool UdpClient::sendData(const QByteArray &data) {
    if (udpSocket->writeDatagram(data, m_serverAddress, m_serverPort) < 0) {
        qDebug() << "Failed to send datagram:" << udpSocket->errorString();
        return false;
    }
    return true;
}

void UdpClient::readPendingDatagrams() {
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress host;
        quint16 port;

        if (udpSocket->readDatagram(datagram.data(), datagram.size(), &host, &port) > 0) {
            qDebug() << "Received datagram from" << host.toString() << ":" << port;
            qDebug() << "Data:" << datagram;
        }
    }
}
